use std::net::{SocketAddr, TcpListener};
use std::time::Duration;

use pdata::internal::data::protogen::collector::logs::v1::{ExportLogsServiceRequest, logs_service_client::LogsServiceClient};
use pdata::internal::data::protogen::collector::metrics::v1::{ExportMetricsServiceRequest, metrics_service_client::MetricsServiceClient};
use pdata::internal::data::protogen::collector::trace::v1::{ExportTraceServiceRequest, trace_service_client::TraceServiceClient};
use rust_collector::receiver::otlp_grpc_receiver::OtlpGrpcReceiver;

fn pick_free_port() -> u16 {
    let l = TcpListener::bind("127.0.0.1:0").expect("bind temp");
    let port = l.local_addr().unwrap().port();
    drop(l);
    port
}

#[tokio::test]
async fn grpc_receiver_accepts_export_requests() {
    let addr: SocketAddr = format!("127.0.0.1:{}", pick_free_port()).parse().unwrap();

    let recv = OtlpGrpcReceiver::new(None, None, None);
    tokio::spawn(async move { let _ = recv.run(addr).await; });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let endpoint = format!("http://{}", addr);

    // traces
    let mut traces = TraceServiceClient::connect(endpoint.clone()).await.unwrap();
    let _ = traces.export(ExportTraceServiceRequest::default()).await.unwrap();

    // metrics
    let mut metrics = MetricsServiceClient::connect(endpoint.clone()).await.unwrap();
    let _ = metrics.export(ExportMetricsServiceRequest::default()).await.unwrap();

    // logs
    let mut logs = LogsServiceClient::connect(endpoint.clone()).await.unwrap();
    let _ = logs.export(ExportLogsServiceRequest::default()).await.unwrap();
}


